package com.bestv.search.common.service.impl;

import com.bestv.search.common.dao.AccessLogDao;
import com.bestv.search.common.dataSource.DataSourceKey;
import com.bestv.search.common.model.AccessLog;
import com.bestv.search.common.service.AccessLogManager;

import java.util.Date;
import java.util.List;

public class AccessLogManagerImpl implements AccessLogManager {

    private AccessLogDao accessLogDao;

    public AccessLogDao getAccessLogDao() {
        return accessLogDao;
    }

    public void setAccessLogDao(AccessLogDao accessLogDao) {
        this.accessLogDao = accessLogDao;
    }

    public void saveAccessLog(DataSourceKey key, AccessLog log) {
        accessLogDao.save(log);
    }

    public void updateAccessLog(DataSourceKey key, AccessLog log) {
        accessLogDao.update(log);
    }

    public void saveOrUpdateAccessLog(DataSourceKey key, List<AccessLog> logs) {
        for (AccessLog log : logs) {
            // Checks this log whether exist in DB
            AccessLog logInDB = accessLogDao.get(log.getType(), log.getAccessLowerTime(), log.getSiteCode(),
                    log.getServerNo());
            if (logInDB != null) {
                // If exists in DB, update this record.
                logInDB.setCount(log.getCount());
                logInDB.setLastUpdateTime(log.getLastUpdateTime());
                accessLogDao.update(logInDB);
            } else {
                // If not exist, insert this record to DB.
                accessLogDao.save(log);
            }
        }
    }

    public AccessLog getAccessLog(DataSourceKey key, int type, Date accessLowerTime, String siteCode, int serverNo) {
        return accessLogDao.get(type, accessLowerTime, siteCode, serverNo);
    }

    public List<AccessLog> getAccessLog(DataSourceKey key, Date accessLowerTime, Date accessUpperTime) {
        return accessLogDao.get(accessLowerTime, accessUpperTime);
    }

    public List<AccessLog> getAccessLog(DataSourceKey key, Date accessLowerTime, Date accessUpperTime, int[] types,
                                        int serverNo) {
        return accessLogDao.get(accessLowerTime, accessUpperTime, types, serverNo);
    }

    public List<AccessLog> getByDate(DataSourceKey key, Date startDate, Date endDate, int[] types) {
        return accessLogDao.getByDate(startDate, endDate, types);
    }

    public List<AccessLog> getAccessLogByMonth(DataSourceKey key, Date startMonth, Date endMonth, int[] types) {
        return accessLogDao.getByMonth(startMonth, endMonth, types);
    }
}